// src/services/weatherService.fixed.js
import { httpRequest } from '../utils/request'
import { WEATHER_CONFIG, ERROR_MESSAGES } from '../utils/constants'

class WeatherService {
  async getCurrentWeather(city) {
    try {
      const params = {
        key: WEATHER_CONFIG.key,
        city: city,
        extensions: 'base',
        output: 'JSON'
      }

      const result = await httpRequest.get('', params)

      console.log('API 响应:', result) // 调试信息

      // 更健壮的响应检查
      if (result && result.status === '1' && result.lives && result.lives.length > 0) {
        return {
          success: true,
          data: result.lives[0]
        }
      } else {
        return {
          success: false,
          error: ERROR_MESSAGES.CITY_NOT_FOUND
        }
      }
    } catch (error) {
      console.error('天气服务错误:', error)
      return {
        success: false,
        error: ERROR_MESSAGES.NETWORK_ERROR
      }
    }
  }

  async getWeatherForecast(city) {
    try {
      const params = {
        key: WEATHER_CONFIG.key,
        city: city,
        extensions: 'all',
        output: 'JSON'
      }

      const result = await httpRequest.get('', params)

      console.log('预报API响应:', result) // 调试信息

      if (result && result.status === '1' && result.forecasts && result.forecasts.length > 0) {
        return {
          success: true,
          data: result.forecasts[0]
        }
      } else {
        return {
          success: false,
          error: ERROR_MESSAGES.CITY_NOT_FOUND
        }
      }
    } catch (error) {
      console.error('天气预报错误:', error)
      return {
        success: false,
        error: ERROR_MESSAGES.NETWORK_ERROR
      }
    }
  }
}

export const weatherService = new WeatherService()